package com.multiple.sources.core.config;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

//AbstractRoutingDataSource的determineCurrentLookupKey()执行时间还要早于切换数据源的切面，切面的order写成1都没用
public class DynamicDataSource extends AbstractRoutingDataSource {
	private Logger log = Logger.getLogger(this.getClass());
	

	public DynamicDataSource() {
		// TODO Auto-generated constructor stub
		System.out.println("数据原设置");
	}

	/**
	 * 数据源为空或者为0时，自动切换至默认数据源，即在配置文件中定义的dataSource数据源
	 */
	@Override
	protected Object determineCurrentLookupKey() throws ServiceException{
		String dataSourceName = DbContextHolder.getDBType();
		if (dataSourceName == null) {
			dataSourceName = Constants.DEFAULT_DATA_SOURCE_NAME;
		} else {
			this.selectDataSource(dataSourceName);
		}
		log.debug("--------> use datasource " + dataSourceName);
		return dataSourceName;
	}

	private void selectDataSource(String dataSourceName) throws ServiceException  {
		// TODO Auto-generated method stub
		Object sid = DbContextHolder.getDBType();
		if (dataSourceName.trim().equals("dataSource")) {
			DbContextHolder.setDBType("dataSource");
			return;
		}
		Object obj = DbContextHolder.getTargetDataSources(dataSourceName);
		if (obj != null && sid.equals(dataSourceName)) {
			return;
		} else {
			DataSource dataSource = this.getDataSource(dataSourceName);
			if (null != dataSource) {
				this.setDataSource(dataSourceName, dataSource);
			} else {
				log.error("--------> not find dataSourceName :" + dataSourceName);
				throw new ServiceException("not find dataSourceName :" + dataSourceName);
				
			}
		}
	}

	private DataSource getDataSource(String dataSourceName) {

		this.selectDataSource(Constants.DEFAULT_DATA_SOURCE_NAME);
		Connection conn = null;
		try {
			conn = this.getConnection();
			StringBuilder builder = new StringBuilder();
			builder.append("SELECT * FROM tenant_data_source where tenant_id=?");
			PreparedStatement ps = conn.prepareStatement(builder.toString());
			ps.setString(1, dataSourceName);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				int type = rs.getInt("type");
				String dataSourceType = rs.getString("data_source_type");
				String url = rs.getString("data_source_url");
				String userName = rs.getString("data_source_username");
				String password = rs.getString("data_source_password");
				String driverClassName = rs.getString("data_source_driver_class_name");
				DataSource dataSource = Constants.buildDataSourceByJdbc(type, dataSourceType, url, userName, password,driverClassName);
				return dataSource;

			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}
	private void setDataSource(String dataSourceName, DataSource dataSource) {
		this.addTargetDataSource(dataSourceName, dataSource);
		DbContextHolder.setDBType(dataSourceName);
	}

	private void addTargetDataSource(String dataSourceName, DataSource dataSource) {
		DbContextHolder.addDataSources(dataSourceName, dataSource);
		System.out.println(DbContextHolder.dataSources());
		super.setTargetDataSources(DbContextHolder.dataSources());
		super.afterPropertiesSet();
		this.setTargetDataSources(DbContextHolder.dataSources());

	}

}
